﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Mvc;
using HotelManageSystem.Domain;
using HotelManageSystem.Domain.Entities;
using HotelManageSystem.Domain.Infrastructure;
using System.Linq;
using HotelManageSystem.Models;
using Telerik.Web.Mvc;

namespace HotelManageSystem.Controllers
{
    public class GodownentryController : Controller
    {
        //
        // GET: /Godownentry/
        private readonly IGodownentryRepository _godownentryRepository;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IEmployeeRepository _employeeRepository;
        private readonly IWarehouseRepository _warehouseRepository;
        private readonly IProductRepository _productRepository;
        private readonly IProductProviderRepository _productProviderRepository;
        private readonly IProductDetailInRepository _productDetailInRepository;
        private readonly IInventoryRepository _inventoryRepository;

        public GodownentryController(IGodownentryRepository godownentryRepository, IInventoryRepository inventoryRepository, IProductDetailInRepository productDetailInRepository, IProductProviderRepository productProviderRepository, IProductRepository productRepository, IUnitOfWork unitOfWork, IEmployeeRepository employeeRepository, IWarehouseRepository warehouseRepository)
        {
            _godownentryRepository = godownentryRepository;
            _employeeRepository = employeeRepository;
            _warehouseRepository = warehouseRepository;
            _productRepository = productRepository;
            _productProviderRepository = productProviderRepository;
            _productDetailInRepository = productDetailInRepository;
            _inventoryRepository = inventoryRepository;
            _unitOfWork = unitOfWork;
        }
        private IList<GodownentryModel> GetAllGodownentries()
        {
            var godownentry = _godownentryRepository.GetAll().AsQueryable();
            IList<GodownentryModel> godownentryModels =
                (from g in godownentry
                 select new GodownentryModel
                 {
                     ID = g.ID,
                     GodownentryID = g.GodownentryID,
                     Stockprice = g.Stockprice,
                     Count = g.Count,
                     Total = g.Total,
                     Datetime = g.Datetime,
                     Billproducer = g.Billproducer,
                     EmployeeName = g.employee.Name,
                     WarehouseName = g.Warehouse.Name,
                     ProductProviderName = g.ProductProvider.Name,
                     ProductName = g.Product.Name,
                 }).ToList();
            return godownentryModels;
        }
        //GridAction特性表示Ajax绑定
        [GridAction]
        public ActionResult TelerikAjax()
        {
            ViewData["warehouses"] = _warehouseRepository.GetAll();
            ViewData["employees"] = _employeeRepository.GetAll();
            ViewData["productproviders"] = _productProviderRepository.GetAll();
            ViewData["products"] = _productRepository.GetAll();
            return View(new GridModel(GetAllGodownentries()));
        }
        public ActionResult Index(string sortMember, int? currentPage)
        {

            ViewData["warehouses"] = _warehouseRepository.GetAll();
            ViewData["employees"] = _employeeRepository.GetAll();
            ViewData["productproviders"] = _productProviderRepository.GetAll();
            ViewData["products"] = _productRepository.GetAll();
            //排序
            ViewData["sortMember"] = sortMember ?? "GodownentryID";
            //分页
            ViewData["currentPage"] = currentPage ?? 1;//当前页
            return View(GetAllGodownentries());
        }
        public ActionResult Creat(Godownentry godownentry)
        {
            var productName = _productRepository.GetAll();
            ViewData["productName"] = new SelectList(productName, "ID", "Name");
            var productProviderName = _productProviderRepository.GetAll();
            ViewData["productProvider"] = new SelectList(productProviderName, "ID", "Name");
            var warehouseName = _warehouseRepository.GetAll();
            ViewData["warehouse"] = new SelectList(warehouseName, "ID", "Name");
            var employeeName = _employeeRepository.GetAll();
            ViewData["employee"] = new SelectList(employeeName, "ID", "Name");
            ViewData["godownentryID"] = "GODOWNENTRY" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                                        DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
            if (Request.HttpMethod == "POST")
            {
                godownentry.Stockprice = Convert.ToDecimal(Request.Form["textprice"]);
                godownentry.Count = Convert.ToInt32(Request.Form["textcount"]);
                godownentry.Total = Convert.ToDecimal(Request.Form["texttotal"]);
                var productID = Request["productName"];
                godownentry.Product = _productRepository.Get(p => p.ID == Convert.ToInt32(productID));
                var productProviderID = Request["productProvider"];
                godownentry.ProductProvider =
                    _productProviderRepository.Get(p => p.ID == Convert.ToInt32(productProviderID));
                var warehouseID = Request["warehouse"];
                godownentry.Warehouse = _warehouseRepository.Get(w => w.ID == Convert.ToInt32(warehouseID));
                var employeeID = Request["employee"];
                godownentry.employee = _employeeRepository.Get(e => e.ID == Convert.ToInt32(employeeID));
                godownentry.GodownentryID = ViewData["godownentryID"].ToString();
                //插入货品的明细编号，入库单价，入库数量
                var productDetail = new ProductDetailIn
                {
                    DetailNumberIn =
                        "PRODUCT" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                        DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second,
                    Product = godownentry.Product,
                    InPrict = Convert.ToDecimal(Request.Form["textprice"]),
                    Count1 = Convert.ToInt32(Request.Form["textcount"]),
                    Total = Convert.ToDecimal(Request.Form["texttotal"])
                };
                _productDetailInRepository.Add(productDetail);
                _unitOfWork.Commit();
                godownentry.ProductDetailIn = _productDetailInRepository.Get(x => x.ID == productDetail.ID);
                _godownentryRepository.Add(godownentry);
                _unitOfWork.Commit();
                //获取入库时货品的ID
                var productid = godownentry.Product.ID;
                //获取库存的所有信息
                var inventory = _inventoryRepository.Get(i => i.Product.ID == productid);
                if (inventory != null)
                {
                    inventory.Count += godownentry.Count;
                    _inventoryRepository.Update(inventory);
                    _unitOfWork.Commit();
                }
                else
                {
                    var invenTory = new Inventory
                    {
                        Count = godownentry.Count,
                        Product = _productRepository.Get(x => x.ID == productid)
                    };
                    _inventoryRepository.Add(invenTory);
                    _unitOfWork.Commit();
                }
                //修改货品信息
                var product = _productRepository.Get(x => x.ID == godownentry.Product.ID);
                product.Price = godownentry.Stockprice;
                //if (inventory != null) product.Count = inventory.Count;
                _productRepository.Update(product);
                _unitOfWork.Commit();
                return RedirectToAction("Index");
            }
            return View();
        }
        [HttpPost]
        [GridAction]
        public ActionResult Delete(int id)
        {
            var godownentry = _godownentryRepository.GetById(id);
            var productdetail = _productDetailInRepository.Get(x => x.ID == Convert.ToInt32(godownentry.ProductDetailIn.ID));
            //删除入库单后库存减少
            var inventory = _inventoryRepository.Get(x => x.Product.ID == godownentry.Product.ID);
            inventory.Count -= godownentry.Count;
            _inventoryRepository.Update(inventory);
            _unitOfWork.Commit();
            _productDetailInRepository.Delete(productdetail);
            _unitOfWork.Commit();
            if (TryUpdateModel(godownentry))
            {
                _godownentryRepository.Delete(godownentry);
                _unitOfWork.Commit();
                return View(new GridModel(GetAllGodownentries()));
            }
            return View();
        }

        public ActionResult Edit(int id)
        {
            //更具入库单的ID检索
            var godownentry = _godownentryRepository.GetById(id);
            //保存入库单在未修改之前的货品数量
            var a = godownentry.Count;
            //获取货品的id
            var pID = godownentry.Product.ID;
            switch (Request.HttpMethod)
            {
                case "POST":
                    {
                        godownentry.Stockprice = Convert.ToDecimal(Request.Form["textprice"]);
                        godownentry.Count = Convert.ToInt32(Request.Form["textcount"]);
                        godownentry.Total = Convert.ToDecimal(Request.Form["texttotal"]);
                        var productID = Request["productName"];
                        godownentry.Product = _productRepository.Get(p => p.ID == Convert.ToInt32(productID));
                        var productProviderID = Request["productProvider"];
                        godownentry.ProductProvider =
                            _productProviderRepository.Get(p => p.ID == Convert.ToInt32(productProviderID));
                        var warehouseID = Request["warehouse"];
                        godownentry.Warehouse = _warehouseRepository.Get(w => w.ID == Convert.ToInt32(warehouseID));
                        var employeeID = Request["employee"];
                        godownentry.employee = _employeeRepository.Get(e => e.ID == Convert.ToInt32(employeeID));
                        var productDetail = _productDetailInRepository.Get(x => x.ID == godownentry.ProductDetailIn.ID);
                        productDetail.InPrict = godownentry.Stockprice;
                        productDetail.Count1 = godownentry.Count;
                        productDetail.Total = godownentry.Total;
                        productDetail.Product = godownentry.Product;
                        productDetail.DetailNumberIn = "PRODUCTIN" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                                                       DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;

                        if (TryUpdateModel(godownentry, null, null, new[] { "productName", "productProvider", "warehouse", "employee" }))
                        {
                            _godownentryRepository.Update(godownentry);
                            _unitOfWork.Commit();
                        }    //货品明细更新
                        _productDetailInRepository.Update(productDetail);
                        _unitOfWork.Commit();
                        //获取入库时货品的ID
                        var productid = godownentry.Product.ID;
                        //判断在入库单修改的时候，用户是否修改了货品名
                        if (pID == productid)
                        {
                            //获取更新后的入库单    
                            var go = _godownentryRepository.GetById(id);
                            //获取库存的所有信息
                            var inventory = _inventoryRepository.Get(i => i.Product.ID == productid);
                            if (go.Count >= a)
                            {
                                var result = go.Count - a;
                                inventory.Count += result;
                                _inventoryRepository.Update(inventory);
                                _unitOfWork.Commit();
                            }
                            else
                            {
                                var result = a - go.Count;
                                inventory.Count -= result;
                                _inventoryRepository.Update(inventory);
                                _unitOfWork.Commit();
                            }
                            return RedirectToAction("Index");
                        }
                        else
                        {
                            //获取更新后的入库单    
                            var go = _godownentryRepository.GetById(id);
                            //获取库存的所有信息
                            var inventory = _inventoryRepository.Get(i => i.Product.ID == go.Product.ID);
                            if (go.Count >= a)
                            {
                                var result = go.Count - a;
                                inventory.Count += result;
                                _inventoryRepository.Update(inventory);
                                _unitOfWork.Commit();
                            }
                            else
                            {
                                var result = a - go.Count;
                                inventory.Count -= result;
                                _inventoryRepository.Update(inventory);
                                _unitOfWork.Commit();
                            }
                            //修改货品信息
                            var product = _productRepository.Get(x => x.ID == godownentry.Product.ID);
                            product.Price = godownentry.Stockprice;
                            product.Count = inventory.Count;
                            _productRepository.Update(product);
                            _unitOfWork.Commit();
                            return RedirectToAction("Index");
                        }

                    }
                default:
                    ViewData["productName"] = new SelectList(_productRepository.GetAll(), "ID", "Name", godownentry.Product.ID);
                    ViewData["productProvider"] = new SelectList(_productProviderRepository.GetAll(), "ID", "Name", godownentry.ProductProvider.ID);
                    ViewData["warehouse"] = new SelectList(_warehouseRepository.GetAll(), "ID", "Name", godownentry.Warehouse.ID);
                    ViewData["employee"] = new SelectList(_employeeRepository.GetAll(), "ID", "Name", godownentry.employee.ID);
                    ViewData["textprice"] = godownentry.Stockprice;
                    ViewData["textcount"] = godownentry.Count;
                    ViewData["texttotal"] = godownentry.Total;
                    return View(godownentry);
            }
        }
    }
}
